package com.baidu.bas.func;

import lombok.val;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.config.MagicFunction;
import org.ssssssss.script.annotation.Comment;
import org.ssssssss.script.annotation.Function;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author liuzhenchuan@foxmail.com
 * @date 2021/1/13
 */
@Component
public class I18nFunction implements MagicFunction {

    @Function
    @Comment("字典转换国际化")
    public static List<Map<String, Object>> convertMap(List<Map<String,Object>> data , HttpServletRequest request) {
        return convertMap("name","ename",data, request);
    }

    /**
     * 将中文字段用英文代替
     * @param cnameField    原有的中文字段
     * @param enameField    需要填充到原有中文字段的英文字段
     * @param data          data 数据
     * @param request       http 请求
     * @return
     */
    @Function
    @Comment("字典转换国际化")
    public static List<Map<String, Object>> convertMap(String cnameField,String enameField, List<Map<String,Object>> data , HttpServletRequest request) {
        val language = request.getHeader("Accept-Language");
        if(language!=null && !language.contains("zh")){
            data.forEach(it->{
                val ename = it.get(enameField);
                if(ename!=null){
                    it.put(cnameField,ename);
                }
            });
        }
        return data;
    }

}
